<?php

namespace App\Http\Controllers\Api;

use App\Jobs\Order\OrderDeliverInfoManage;
use App\Jobs\Shop\ShopOrderDeliverInfoManage;
use App\Lib\WeApp\WeApp;
use App\Models\Shop\WxShopOrder;
use App\Models\User\WxUser;
use App\Models\User\WxUserCoinRecord;
use App\Models\WxDomainAuth;
use App\Models\WxOrder;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class AggregateController extends BaseController
{
    /**
     * 对用户聚合
     * @param Request $request
     */
    public function user_hanlder(Request $request){
        $action = $request->action;
        if(_empty_($action)){
            return $this->fail(200001);
        }
        switch ($action) {
            case "mute":
                return $this->mute_user($request);
                break;
            case "unmute":
                return $this->unmute_user($request);
                break;
            case "ban":
                return $this->ban_user($request);
                break;
            case "unban":
                return $this->unban_user($request);
                break;
            case "authorization":
                return $this->get_user_authorization($request);
                break;
            case "mini_deliver_info_confirm_first_order":
                return $this->mini_deliver_info_confirm_first_order($request);
                break;
            case "ban_mute_detail":
                return $this->ban_mute_detail($request);
                break;
            default:
                echo "Your favorite color is neither red, blue, nor green!";
        }

    }


    private function ban_mute_detail(Request &$request){
        $user_id = $request->user_id;
        if(_empty_($user_id)){
            return $this->fail(503002);
        }
        $the_user = WxUser::find($user_id);
        if(_empty_($the_user)){
            return $this->fail(200003);
        }
        if($the_user->user_state === 2){
            $ban_until = get_user_meta($the_user->id, 'ban_until', 's');
            if(time() > $ban_until){
                // 解除封号
                if(UserUtils::unlock_user($the_user, 2)){
                    $the_user->state_tip = '正常用户';
                    $the_user->user_state = 0;
                }
            }
            if($ban_until && $the_user->user_state === 2){
                $ban_until_ = Carbon::createFromTimestamp($ban_until);
                $the_user->state_tip = '该用户被封号至'.$ban_until_->toDateTimeString();
                $the_user->ban_until = $ban_until_->toDateTimeString();
                $secondsDifference = $ban_until_->diffInSeconds(Carbon::now());
                $hoursDifference = round($secondsDifference / 3600, 2);

                global $__MINI_GLOBAL_TENANT_ID__;
                $tmp_tenant_id = -1;
                if($__MINI_GLOBAL_TENANT_ID__ != $the_user->tenant_id){
                    $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                    $__MINI_GLOBAL_TENANT_ID__ = $the_user->tenant_id;
                }
                $the_user->cost_balance = round($hoursDifference * Settings::get('app_unban_one_hour_balance', 1.0, true), 2);
                if($tmp_tenant_id > 0){
                    $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
                }
            }
        }else if($the_user->user_state === 3){
            $mute_until = get_user_meta($the_user->id, 'mute_until', 's');
            if(time() > $mute_until){
                // 解除禁言
                if(UserUtils::unlock_user($the_user, 3)){
                    $the_user->state_tip = '正常用户';
                    $the_user->user_state = 0;
                }
            }
            if($mute_until && $the_user->user_state === 3){
                $mute_until_ = Carbon::createFromTimestamp($mute_until);
                $the_user->state_tip = '该用户被禁言至'.$mute_until_->toDateTimeString();
                $the_user->mute_until = $mute_until_->toDateTimeString();
                $secondsDifference = $mute_until_->diffInSeconds(Carbon::now());
                $hoursDifference = round($secondsDifference / 3600, 2);

                global $__MINI_GLOBAL_TENANT_ID__;
                $tmp_tenant_id = -1;
                if($__MINI_GLOBAL_TENANT_ID__ != $the_user->tenant_id){
                    $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                    $__MINI_GLOBAL_TENANT_ID__ = $the_user->tenant_id;
                }
                $the_user->cost_balance = round($hoursDifference * Settings::get('app_unmute_one_hour_balance', 0.5, true), 2);
                if($tmp_tenant_id > 0){
                    $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
                }


            }
        }
        return $this->success($the_user);
    }


    /** 获取配置
     * @param Request $request
     */
    public function config(Request $request){
        $type = _empty_default_($request->type, '');
        if(_empty_($type)){
            return $this->fail(200001);
        }
        switch ($type) {
            case "inspire":
                return $this->inspire_config($request);
                break;
            case "jssdk":
                return $this->get_jssdk_config($request);
                break;
            case "voter-template-type":
                return $this->get_voter_template_type($request);
                break;
            case "get-withpara-mpservicer-code":
                return $this->get_withpara_mpservicer_code($request);
                break;
            case 'note-config':
                return $this->get_note_config($request);
                break;
            default:
                echo "Your favorite color is neither red, blue, nor green!";
        }
    }

    private function get_note_config(Request &$request){
        $config = [
            'middle' => [
                'box' => Settings::get('app_note_middle_box', [])
            ],
            'bottom' => [
                'box' => Settings::get('app_note_bottom_box', [])
            ]
        ];
        return $this->success($config);
    }

    private function get_user_authorization(Request &$request){
        $uid = $request->uid;
        $user_id = _empty_default_($request->user_id, 0);
        $domain = _empty_default_($request->domain, '');
        if(_empty_($uid) && _empty_($domain) && _empty_($user_id)){
            return $this->fail(503002);
        }
        if(!_empty_($user_id)){
            $auth = WxDomainAuth::where('user_id', $user_id)->first();
            if($auth){
                return $this->success(['id'=>$auth->id, 'user_id'=>$auth->user_id]);
            }else{
                return $this->fail(200003);
            }
        }else if(!_empty_($domain)){
            $auth = WxDomainAuth::where('domain_1', $domain)->orWhere('domain_2', $domain)
                ->orWhere('domain_3', $domain)->orWhere('domain_4', $domain)
                ->orWhere('domain_5', $domain)->orWhere('domain_6', $domain)
                ->orWhere('domain_7', $domain)->first();
        }else{
            $auth = WxDomainAuth::where('user_id', $uid)->first();
        }
        if($auth){
            return $this->success($auth);
        }
        return $this->fail(200003);
    }

    private function get_withpara_mpservicer_code(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200000);
        }
        global $__MINI_GLOBAL_TENANT_ID__;
        $action = _empty_default_($request->code_action, 'bind');
        $scene = _empty_default_($request->scene, '');
        $scene_id = _empty_default_($request->scene_id, '');
        if($action == 'scene'){
            if(_empty_($scene)){
                return $this->fail(200001);
            }
            $scene_str = 'user:scene:'.$uid.':'.$scene.':'.$__MINI_GLOBAL_TENANT_ID__;
            if($scene_id > 0){
                $scene_str .= ':'.$scene_id;
            }
        }else{
            $scene_str = 'user:bind:'.$uid;
        }
        $weapp = new WeApp('mp');
        $mpServicer = $weapp->getMpServicer();
        try {
            $url = $mpServicer->getQrCodeWithPara(0, $scene_str);
        }catch (\Exception $e){
            return $this->fail(200006, [], '生成公众号二维码失败，请检查[全局配置-支付-微信-公众号]');
        }
        if($url){
            $qrCode = QrCode::format('png')->size(300)->generate($url);
            $image = Image::make($qrCode);

            if($action == 'bind'){
                $image->resizeCanvas(300, 300 + 60, 'bottom', false, '#ffffff'); // 增加高度，保持宽高比，背景色为白色
                $mp_app_name = Settings::get('mp_app_name', '');
                $text_tip = '关注'.$mp_app_name.'公众号，可以更方便通知到您';
                if(mb_strlen($mp_app_name) > 4){
                    $text_tip = '关注'.$mp_app_name.'公众号';
                }
                $image->text($text_tip, 150, 40, function($font){
                    $font->file(public_path('storage/font/DingTalk_JinBuTi_Regular.ttf')); // 字体文件路径
                    $font->size(13); // 字体大小
                    $font->color('#000000'); // 字体颜色
                    $font->align('center'); // 水平对齐
                    $font->valign('top'); // 垂直对齐
                });
            }

            $base64 = 'data:image/png;base64,' . base64_encode($image->encode('png')->getEncoded());

            return $this->success($base64);
        }
        return $this->fail(200006);
    }

    private function get_voter_template_type(Request &$request){
        return $this->success([
            [
                "id" => 0,
                "name" => "默认"
            ]
        ]);
    }


    private function get_jssdk_config(Request &$request){
        $url = _empty_default_($request->url, Settings::get('app_h5_home', 'https://mini.h5.minisns.cn'));
        $weapp = new WeApp('mp');
        $mps = $weapp->getMpServicer();
        if($mps){
            return $this->success($mps->getJsSdkConfig($url));
        }
        return $this->fail(200008, [], '管理员未配置公众号的appid或appsecret');
    }

    private function mini_deliver_info_confirm_first_order(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200000);
        }
        $order = WxOrder::where('user_id', $uid)->whereNotNull('order_serial_number')->where('order_serial_number', '<>', '')->where('order_serial_platform', 0)
            ->where('order_serial_platform_type', 'mini')->where('order_state', 5)->orderBy('id', 'desc')->first();
        if($order){
            OrderDeliverInfoManage::dispatch('query', $order->id);
            return $this->success([
                'type' => 'order',
                'transaction_id' => $order->order_serial_number,
            ]);
        }else{
            $shop_order = WxShopOrder::withTrashed()->where('user_id', $uid)->where('pay_status', 2)->whereNull('parent_order_id')->whereIn('status', [8, 10])->whereNotNull('serial_number')->where('serial_number', '<>', '')->where('serial_platform', 0)
                ->where('serial_platform_type', 'mini')->orderBy('id', 'desc')->first();
            if($shop_order){
                if($shop_order->status == 8){
                    ShopOrderDeliverInfoManage::dispatch('query', $shop_order->id, null);
                }else if($shop_order->status == 10){
                    ShopOrderDeliverInfoManage::dispatch('virtual-query', $shop_order->id, null);
                }else if($shop_order->status == 9){
                    ShopOrderDeliverInfoManage::dispatch('virtual-upload', $shop_order->id, null);
                }
                return $this->success([
                    'type' => 'shop_order',
                    'transaction_id' => $shop_order->serial_number,
                ]);
            }
        }
        return $this->fail(200003);
    }

    private function unban_user(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200000);
        }

        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000);
        }

        // 参数
        $user_id = _empty_default_($request->user_id, 0);
        if(_empty_($user_id)){
            return $this->fail(200001);
        }
        $the_user = WxUser::find($user_id);
        if(UserUtils::unlock_user($the_user, 2)){
            return $this->success([], 200, '已解除');
        }else{
            return $this->fail(200002);
        }
    }

    private function unmute_user(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200000);
        }

        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000);
        }

        // 参数
        $user_id = _empty_default_($request->user_id, 0);
        if(_empty_($user_id)){
            return $this->fail(200001);
        }
        $the_user = WxUser::find($user_id);
        if(UserUtils::unlock_user($the_user, 3)){
            return $this->success([], 200, '已解除');
        }else{
            return $this->fail(200002);
        }
    }

    private function ban_user(Request &$request){
        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200000);
        }

        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000);
        }

        // 参数
        $user_id = _empty_default_($request->user_id, 0);
        if(_empty_($user_id)){
            return $this->fail(200001);
        }

        $days = _empty_default_($request->days, 0);
        if(_empty_($days)){
            return $this->fail(200001);
        }

        if(!in_array($days, [7, 30, 90, 3650])){
            return $this->fail(200004);
        }

        $the_user = WxUser::find($user_id);
        if(UserUtils::lock_user_incre($the_user, 2, $days * 3600 * 24)){
            return $this->success([], 200, '已将该用户封号'.$days.'天');
        }else{
            return $this->fail(200002);
        }
    }


    private function mute_user(Request &$request){

        $uid = $request->uid;
        if(_empty_($uid)){
            return $this->fail(200000);
        }

        if(!UserUtils::is_mini_supder_admin($uid)){
            return $this->fail(200000);
        }

        // 参数
        $user_id = _empty_default_($request->user_id, 0);
        if(_empty_($user_id)){
            return $this->fail(200001);
        }

        $days = _empty_default_($request->days, 0);
        if(_empty_($days)){
            return $this->fail(200001);
        }

        if(!in_array($days, [3, 7, 30, 90])){
            return $this->fail(200004);
        }

        $the_user = WxUser::find($user_id);
        if(UserUtils::lock_user_incre($the_user, 3, $days * 3600 * 24)){
            return $this->success([], 200, '已将该用户禁言'.$days.'天');
        }else{
            return $this->fail(200002);
        }
    }

    private function inspire_config(Request &$request){
        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        if(_empty_($__MINI_GLOBAL_CURRENT_USER_ID__)){
            return $this->fail(503002);
        }
        global $__MINI_GLOBAL_DEVICE__;
        if($request->isMethod('GET')){
            // 总共观看了多少次，获得了多少金币，今天观看了几次，今天上限次数
            $today_count = WxUserCoinRecord::where([
                ['user_id', '=', $__MINI_GLOBAL_CURRENT_USER_ID__],
                ['type', '=', 10],
                ['created_at', '>=', Carbon::today()]
            ])->count();
            $total_count = WxUserCoinRecord::where([
                ['user_id', '=', $__MINI_GLOBAL_CURRENT_USER_ID__],
                ['type', '=', 10]
            ])->count();

            $total_coin_count = WxUserCoinRecord::where([
                ['user_id', '=', $__MINI_GLOBAL_CURRENT_USER_ID__],
                ['type', '=', 10]
            ])->sum('incre');

            if($__MINI_GLOBAL_DEVICE__ == 'mp'){
                $every_day_max = Settings::get('ad_mp_reward_every_day_times', 10);
            }else{
                $every_day_max = Settings::get('ad_uni_reward_every_day_times', 10);
            }

            return $this->success([
                'total_times' => $total_count,
                'today_times' => $today_count,
                'total_coins' => $total_coin_count,
                'every_day_max' => $every_day_max
            ]);
        }else if($request->isMethod('POST')){

        }
    }

}
